/* eslint-disable */
import React, { Component } from 'react';
import "animate.css";
import ReactCSSTransitionGroup from "react-addons-css-transition-group";

/**
 * 动画组件
 * 将需要添加动画的组件以children的形式传入 
 * 需要传入动画类名 动画选择请跳至 https://daneden.github.io/animate.css/
 * ReactCSSTransitionGroup 文档请跳至 https://www.jianshu.com/p/52a8bdbd2acf
 */
class Animation extends Component{

  static defaultProps = {
    children: null,
    className: "wobble",           // 在animation.css中的动画类名
    transitionOption: {},          // 动画效果配置项
  }

  componentDidMount() {
    this.setChildrenClass();
  }

  // 获取动画配置
  getTransitionOption = () => {
    let defaultOpt = {
      transitionEnter: true,
      transitionLeave: true,
      transitionEnterTimeout: 1500,
      transitionLeaveTimeout: 1500,
      transitionName: "animated"
    }
    return Object.assign({}, defaultOpt, this.props.transitionOption);
  }

  // 修改子组件的类名  添加上动画类名
  setChildrenClass = () => {
    let { children, className } = this.props;
    
    // 当只有一个子组件时 children为对象 需要转为数组
    if(children.constructor === Object) {
      children = [children]
    }

    children = children.map((child, i) => {
      return React.cloneElement(
        child, 
        { 
          className : child.props.className + ' animated ' + className,
          key: i 
        }
      )
    });
    return children
  }

  render() {
    return (
      <ReactCSSTransitionGroup
        { ...this.getTransitionOption() }
      >
        { this.setChildrenClass() }
      </ReactCSSTransitionGroup>
    )
  }

}

export default Animation